package ch.simas.javaee6examples.service;

import ch.simas.javaee6examples.model.Employee;
import ch.simas.javaee6examples.service.interceptor.TraceInterceptor;
import java.util.List;
import javax.ejb.Stateless;
import javax.interceptor.Interceptors;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Simon Martinelli
 */
@Stateless
@Interceptors(TraceInterceptor.class)
public class EmployeeService {

    @PersistenceContext
    EntityManager em;

    public List<Employee> findAll() {

        Query query = em.createQuery("SELECT e FROM Employee e ORDER BY e.name");
        return query.getResultList();
    }

    public Employee save(Employee employee) {
        if (employee.getId() == null) {
            em.persist(employee);
            return employee;
        } else {
            return em.merge(employee);
        }
    }

    public void deleteEntity(Employee employee) {
        Employee fromDB = em.find(Employee.class, employee.getId());
        em.remove(fromDB);
    }
}
